<template>
  <view class="container">
 
    
    <!-- 球馆列表 -->
    <view class="venue-list-container">
      <view class="venue-grid">
        <view 
          v-for="(venue, index) in venueList" 
          :key="index" 
          class="venue-card" 
          @click="goToMiniProgram(venue.appId)"
        >
          <image :src="venue.images[0]" mode="aspectFill" class="venue-image" />
          <view class="venue-content">
            <view class="venue-title">{{ venue.name }}</view>
            <view class="venue-desc">{{ venue.description }}</view>
            <view class="venue-address">{{ getPrimaryAddress(venue) }}</view>
            <view class="venue-distance">距离：{{ venue.distance || '计算中...' }}</view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import venueConfig from '../../common/venueConfig.json';

export default {
  data() {
    return {
      venueList: venueConfig.venues || [],
      userLocation: null
    };
  },
  
  mounted() {
    this.getUserLocation();
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    getPrimaryAddress(venue) {
      if (venue.addresses && venue.addresses.length > 0) {
        const primaryAddress = venue.addresses.find(addr => addr.isPrimary) || venue.addresses[0];
        return primaryAddress.address || '';
      }
      return '';
    },
    getDistance(lat1, lon1, lat2, lon2) {
      // 注意：参数顺序是 (纬度, 经度)
      
      // 将GCJ-02坐标转换为WGS-84坐标（球馆配置中的坐标是WGS-84）
      const wgs2 = this.gcj02ToWgs84(lat1, lon1);
      
      const R = 6371; // 地球半径，单位千米
      const dLat = this.deg2rad(lat2 - wgs2.lat);
      const dLon = this.deg2rad(lon2 - wgs2.lng);
      const a = 
        Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(this.deg2rad(wgs2.lat)) * Math.cos(this.deg2rad(lat2)) * 
        Math.sin(dLon/2) * Math.sin(dLon/2);
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
      const distance = R * c; // 距离，单位千米
      
      return distance;
    },
    
    // GCJ-02坐标转WGS-84坐标
    gcj02ToWgs84(lat, lng) {
      if (this.outOfChina(lat, lng)) {
        return { lat: lat, lng: lng };
      }
      
      let dlat = this.transformLat(lng - 105.0, lat - 35.0);
      let dlng = this.transformLng(lng - 105.0, lat - 35.0);
      const radlat = lat / 180.0 * Math.PI;
      let magic = Math.sin(radlat);
      magic = 1 - 0.00669342162296594323 * magic * magic;
      const sqrtmagic = Math.sqrt(magic);
      dlat = (dlat * 180.0) / ((6378245.0 * (1 - 0.00669342162296594323)) / (magic * sqrtmagic) * Math.PI);
      dlng = (dlng * 180.0) / (6378245.0 / sqrtmagic * Math.cos(radlat) * Math.PI);
      const mglat = lat - dlat;
      const mglng = lng - dlng;
      return { lat: mglat, lng: mglng };
    },
    
    outOfChina(lat, lng) {
      return (lng < 72.004 || lng > 137.8347) || ((lat < 0.8293 || lat > 55.8271) || false);
    },
    
    transformLat(lng, lat) {
      let ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
      ret += (20.0 * Math.sin(6.0 * lng * Math.PI) + 20.0 * Math.sin(2.0 * lng * Math.PI)) * 2.0 / 3.0;
      ret += (20.0 * Math.sin(lat * Math.PI) + 40.0 * Math.sin(lat / 3.0 * Math.PI)) * 2.0 / 3.0;
      ret += (160.0 * Math.sin(lat / 12.0 * Math.PI) + 320 * Math.sin(lat * Math.PI / 30.0)) * 2.0 / 3.0;
      return ret;
    },
    
    transformLng(lng, lat) {
      let ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
      ret += (20.0 * Math.sin(6.0 * lng * Math.PI) + 20.0 * Math.sin(2.0 * lng * Math.PI)) * 2.0 / 3.0;
      ret += (20.0 * Math.sin(lng * Math.PI) + 40.0 * Math.sin(lng / 3.0 * Math.PI)) * 2.0 / 3.0;
      ret += (150.0 * Math.sin(lng / 12.0 * Math.PI) + 300.0 * Math.sin(lng / 30.0 * Math.PI)) * 2.0 / 3.0;
      return ret;
    },
    
    deg2rad(deg) {
      return deg * (Math.PI/180);
    },
    
    getUserLocation() {
      uni.getLocation({
        type: 'gcj02',
        success: (res) => {
          this.userLocation = {
            latitude: res.latitude,
            longitude: res.longitude
          };
          console.log('获取用户位置成功:', this.userLocation);
          
          // 获取位置成功后，立即计算距离
          this.calculateDistances();
        },
        fail: (err) => {
          console.error('获取位置失败', err);
          // 设置默认位置（广州）
          this.userLocation = {
            latitude: 23.025036,
            longitude: 113.713612
          };
          // 使用默认位置计算距离
          this.calculateDistances();
        }
      });
    },
     
     calculateDistances() {
       // 确保用户位置和venues都已加载
       if (!this.userLocation || !this.venueList || this.venueList.length === 0) {
         console.log('calculateDistances: 数据未准备好', {
           userLocation: !!this.userLocation,
           venues: this.venueList ? this.venueList.length : 0
         });
         return;
       }
       
       const venuesWithDistance = this.venueList.map(venue => {
         if (venue.addresses && venue.addresses.length > 0) {
           // 使用主要地址或第一个地址
           const targetAddress = venue.addresses.find(addr => addr.isPrimary) || venue.addresses[0];
           
           const distance = this.getDistance(
             this.userLocation.latitude,
             this.userLocation.longitude,
             targetAddress.latitude,
             targetAddress.longitude
           );
           return {
             ...venue,
             distance: distance.toFixed(1) + ' km'
           };
         }
         return {
           ...venue,
           distance: '未知'
         };
       });
       
       // 根据距离从小到大排序
       venuesWithDistance.sort((a, b) => {
         const distanceA = parseFloat(a.distance);
         const distanceB = parseFloat(b.distance);
         if (isNaN(distanceA)) return 1;
         if (isNaN(distanceB)) return -1;
         return distanceA - distanceB;
       });
       
       // 更新venueList数组
       this.venueList = venuesWithDistance;
     },
     
     goToMiniProgram(appId) {
      if (appId) {
        uni.navigateToMiniProgram({
          appId: appId,
          success: function(res) {
            console.log('跳转小程序成功');
          }
        });
      } else {
        uni.showToast({
          title: '该场馆暂不支持小程序跳转',
          icon: 'none'
        });
      }
    }
  }
};
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background-color: #f8f9fa;
}

// 导航栏样式
.custom-nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  padding: 0 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-back {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .nav-back-text {
    font-size: 40rpx;
    color: #333;
    font-weight: bold;
  }
}

.nav-bar-title {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
}

.nav-placeholder {
  width: 60rpx;
}

// 球馆列表样式
.venue-list-container {
  padding: 30rpx;
}

.venue-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20rpx;
}

.venue-card {
  background: #fff;
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  transition: transform 0.2s ease, box-shadow 0.2s ease;
  
  &:active {
    transform: scale(0.98);
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.12);
  }
}

.venue-image {
  width: 100%;
  height: 240rpx;
  background-color: #f5f5f5;
}

.venue-content {
  padding: 24rpx;
}

.venue-title {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 12rpx;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.venue-desc {
  font-size: 24rpx;
  color: #666;
  line-height: 1.5;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  margin-bottom: 8rpx;
}

.venue-address {
  font-size: 22rpx;
  color: #999;
  line-height: 1.4;
  overflow: hidden;
  // text-overflow: ellipsis;
  // white-space: nowrap;
  margin-bottom: 6rpx;
}

.venue-distance {
  font-size: 22rpx;
  color: #42CF7F;
  font-weight: 500;
}

// 响应式设计
@media screen and (max-width: 750rpx) {
  .venue-grid {
    gap: 15rpx;
  }
  
  .venue-list-container {
    padding: 20rpx;
  }
}
</style>